clear all; close all;

% Generate input signals
E5aI_sc = SecondaryPRNCode('E5aI');
E5aQ_sc = SecondaryPRNCode('E5aQ');
NumberOfDataBits = 25;
SNR = 20; % dB
Amplitude = 1;
CarrierPhase = pi/3;
SVID = 12;
StdNoise = Amplitude^2/(2*db2pow(SNR));
NumberOfCorrelatorOut = NumberOfDataBits*E5aI_sc.NumberOfChips;
DataBits = -2*floor(2*rand(1, NumberOfDataBits)) +1;

N = NumberOfCorrelatorOut;
SCI = BitSynchronization.extendCode(E5aI_sc.getCode(1, 0), N);
SCQ = BitSynchronization.extendCode(E5aQ_sc.getCode(SVID, 0), N);
UpsampledDataBits = zeros(1, N);
DataRatio = N/NumberOfDataBits; 
for i=1:N
	UpsampledDataBits(i) = DataBits(floor((i-1)/DataRatio)+1);
end

Noise = StdNoise*(randn(2, N) + j*rand(2, N));
CorrelatorOut(1,:) = Amplitude*UpsampledDataBits.*SCI + Noise(1,:);
CorrelatorOut(2,:) = Amplitude*SCQ + Noise(2,:);
CorrelatorOut = CorrelatorOut * exp(j*CarrierPhase);
TimeShiftInit = 0.0005;
TimeShiftStd = 1e-8;
TimeShiftStdThreshold = TimeShiftStd*2;
FrequencyShiftInit = 5;
FrequencyShiftStd = 1;
FrequencyShiftStdThreshold = FrequencyShiftStd*2;
TimeShift = TimeShiftInit + TimeShiftStd*randn(1, N); 
FrequencyShift = FrequencyShiftInit + FrequencyShiftStd*randn(1, N); 

% Start bit synchronization
bitsync = BitSynchronization('E5a', 12, 'BitSyncE5a_tb.txt');

for i=1:N
	i
	bitsync.addToBuffer(CorrelatorOut(:,i), FrequencyShift(i), TimeShift(i));
	if (bitsync.NumberOfCorrelatorOutInBuffer == bitsync.CorrelatorOutBufferSize)
		fprintf(1, 'Buffer is full, ok...\n');
		if (bitsync.checkFrequencyTimeShiftStd(FrequencyShiftStdThreshold,...
																					 TimeShiftStdThreshold))
			fprintf(1, 'Thresholds ok...\n');
			insync = bitsync.checkBitSynchronization();
			if (insync(1) && insync(2))
				fprintf(1, 'In sync ok! \n');
				bitsync.storeBitSoftInformation();
			end
		else
			fprintf(1, 'Above std. thresholds! \n');
			break;	
		end		
	end
end
